import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sp_util/sp_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yp/config/event_bus.dart';
import 'package:yp/router.dart';

// import 'cghsh/cg_app_routes.dart';
// import 'cghsh/common/cg_common_data.dart';
// import 'cghsh/common/cg_common_macro.dart';
import 'config/config.dart';
import 'pages/main/logic.dart';
import 'services/api.dart';

/// showToast二次封装
///
///
toast(String message) {
  showToast(
    message,
    textPadding: EdgeInsets.symmetric(vertical: 7, horizontal: 10),
  );
}

/// showToast二次封装，隐藏正在执行中的提示。
toastDismissOther(String message) {
  showToast(
    message,
    textPadding: EdgeInsets.symmetric(vertical: 7, horizontal: 10),
    dismissOtherToast: true,
  );
}

/// showToast二次封装，高等级提示。
toastWarn(String message) {
  showToast(
    message,
    textPadding: EdgeInsets.symmetric(vertical: 30, horizontal: 30),
    backgroundColor: Colors.red,
    textStyle: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
  );
}

/// 十六进制颜色，
/// hex, 十六进制值，例如：0xffffff,
/// alpha, 透明度 [0.0,1.0]
Color hexColor(int hex, {double alpha = 1}) {
  if (alpha < 0) {
    alpha = 0;
  } else if (alpha > 1) {
    alpha = 1;
  }
  return Color.fromRGBO((hex & 0xFF0000) >> 16, (hex & 0x00FF00) >> 8,
      (hex & 0x0000FF) >> 0, alpha);
}

/// 取随机颜色
///
///
Color randomColor() {
  var red = Random.secure().nextInt(255);
  var greed = Random.secure().nextInt(255);
  var blue = Random.secure().nextInt(255);
  return Color.fromARGB(255, red, greed, blue);
}

Map<String, dynamic> buildParams({
  String method,
  Map<String, dynamic> params,
}) {
  var reqBase64 = EncryptUtil.encodeBase64(jsonEncode(params));
  var timestamp = DateUtil.formatDateStr(DateTime.now().toString(),
      format: "yyyyMMddHHmmss");
  String sign = "";

  /// cache
  ///
  var salt = SpUtil.getString('salt', defValue: '');
  var sid = SpUtil.getString('sid', defValue: '');
  if (sid.isNotEmpty && salt.isNotEmpty) {
    String s = salt +
        "method" +
        method +
        "params" +
        reqBase64 +
        "sid" +
        sid +
        "timestamp" +
        timestamp +
        salt;
    var bytes = utf8.encode(s); // data being hashed
    sign = sha1.convert(bytes).toString().toLowerCase();
  } else {
    String s = reqBase64 + "20001" + timestamp + method;
    var bytes = utf8.encode(s); // data being hashed
    //sign = sha1.convert(bytes).toString().toLowerCase();
    sign = EncryptUtil.encodeMd5(s);
  }
  Map<String, dynamic> newParams = {
    "method": method,
    "app_key": "20001",
    "params": reqBase64,
    "timestamp": timestamp,
    "sign": sign,
    // "sid": sid,
  };
  return newParams;
}

double setWidth(double width) {
  return ScreenUtil().setWidth(width);
}

double setHeight(double width) {
  return ScreenUtil().setHeight(width);
}

String parsePrice(dynamic num, {bool isFloat = false}) {
  String str;
  if (num.runtimeType == String) {
    str = double.parse(num).toString();
  } else {
    str = num.toString();
  }
  if (!isFloat) {
    if (str.endsWith(".0")) {
      str = str.replaceAll(".0", '');
    }
    if (str.endsWith(".00")) {
      str = str.replaceAll(".00", '');
    }
  } else {
    if (!str.contains(".")) {
      str = str + ".00";
    }
    if (str.endsWith(".0")) {
      str = str.replaceAll(".0", '.00');
    }
    if (str.endsWith(".00")) {
      str = str.replaceAll(".00", '.00');
    }
  }
  return str;
}

Color getColorFromHex(String hexColor) {
  return Color(int.parse(hexColor.replaceFirst('#', '0xFF')));
}

// 界面跳转 逻辑在小程序在首页index.wpy jumpUrl方法，代码1209行左右
void jump({
  String url,
  dynamic model,
}) {
  final MainLogic mainLogic = Get.put(MainLogic());

  print('1111111111=========1111111111  url = $url, model = $model');
  if (SpUtil.getString('token') == null || SpUtil.getString('token').isEmpty) {
    Get.toNamed(RouteConfig.mallLogin);
    return;
  }
  if (url != null && url != '') {
    if (url == '3') {
      // print(model);
      if (model['icon_name'] == '本地生活') {
        Get.toNamed(
          RouteConfig.localLife,
          arguments: {'model': model},
        );
      } else {
        // 装修活动（活动详情）
        Get.toNamed(
          RouteConfig.decorationActivities,
          arguments: {'linktarget': '${model['linktarget']}'},
        );
      }
    } else if (url == '4') {
      // 商品搜索列表 (虚拟分类)
      Get.toNamed(
        RouteConfig.commoditySearchList,
        parameters: {'linktarget': '${model['linktarget']}'},
      );
    } else if (url == '10') {
      // 领券中心
      Get.toNamed(RouteConfig.collectCouponsCentre);
    } else if (url == '2') {
      String itemNumId = ''; //goodsJson['default_item_num_id'].toString();
      String styleNumId =
          model['linktarget']; //goodsJson['style_num_id'].toString();
      // String shopId = SpUtil.getInt('storeShopNum')
      //     .toString(); //goodsJson['shop_num_id'].toString();
      String shopId = model['shop_id'] == null
          ? SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']?.toString()
          : model['shop_id'].toString();
      String cat1Id = ''; //goodsJson['cat1_id'].toString();
      Get.toNamed(RouteConfig.goodsDetail, arguments: {
        'itemNumId': itemNumId,
        'styleNumId': styleNumId,
        'shopId': shopId,
        'cat1Id': cat1Id,
        'typeIndex': 0,
      });
    } else if (url == '7') {
      var cs = model['linktarget'];
      //秒杀
      Get.toNamed(RouteConfig.seckillHome, parameters: {'cs': cs});
    } else if (url == '22') {
      // 本地生活
      // Get.toNamed(
      //   RouteConfig.localLife,
      //   arguments: {'model': model},
      // );
      // 22应该是店铺主页
      getAndGoThirdShop(int.parse(model["linktarget"].toString()));
    } else if (url == '9') {
      // 拼团
      Get.toNamed(
        //salesRankings 拼团热销榜   collage  拼团首页UI
        RouteConfig.collage,
        arguments: {'model': model},
      );
    } else if (url == '13') {
      // 大转盘
      Get.toNamed(RouteConfig.turntable, arguments: model);
    } else if (url == '28') {
      // 发现
      Get.toNamed(RouteConfig.discover);
    } else if (url == '8') {
      // 积分商城
      Get.toNamed(RouteConfig.integralMall);
    } else if (url == '29') {
      // 申请慧达人
      var params = {
        'leader_usr_num_id': SpUtil.getInt('empeNumId'),
        "access_token": SpUtil.getString('token'),
      };
      Api.applyquery(params).listen((event) {
        if (event['code'] == 0) {
          if (event['distribution_salesperson_apply'] == null) {
            var params2 = {
              'access_token': SpUtil.getString('token'),
              'mobile': SpUtil.getString('number'),
            };
            Api.searchMember(params2).listen((event) {
              if (event['code'] == 0) {
                Get.toNamed(RouteConfig.applyExpert, arguments: event);
              } else {
                toast('转跳失败');
              }
            });
          } else {
            // Get.toNamed(RouteConfig.applyExpert);
            Get.toNamed(RouteConfig.expertUnderReview);
          }
        }
      });
    } else if (url == '12') {
      // 预售
      Get.toNamed(RouteConfig.preSaleActive, arguments: {
        'linktarget': '${model['linktarget']}',
        'shopId': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']?.toString()
      });
    } else if (url == '1') {
      print('粮油跳转${model["linktarget"]}');
      Timer.periodic(Duration(seconds: 1), (timer) {
        print("SwitchTabEvent = ===${model["linktarget"]}");
        timer.cancel();

        eventBus.fire(SwitchTabEvent(model["linktarget"].toString()));
      });
      mainLogic.switchTap(1);
    } else if (url == '32') {
      // 超级团
      Get.toNamed(RouteConfig.surplusMarketPage);
    } else if (url == '11') {
      // print('燃气缴费          = ${model['linktarget']}'); // 11
      if (kIsWeb) {
        toast("请至应用市场下载“壹品慧”APP或微信搜索“壹品慧”小程序使用该功能。");
      } else {
        launchWeChatMiniProgram(
          username: model['linktarget'],
          path: '',
        );
      }
    } else if (url == '31') {
      // 定金预售
      print(model);
      // return;
      Get.toNamed(RouteConfig.fontMoneySalePage,
          arguments: {'targetType': model['linktarget']});
    } else if (url == '23') {
      // webview

      if (kIsWeb) {
        launch(model['linktarget']);
      } else {
        Get.toNamed(RouteConfig.webview,
            arguments: {'url': model['linktarget']});
      }
    } else if (url == '34') {
      // 燃气缴费
      // intoCGPage(CGRouteSetting.home_query_userInfo);
    } else if (url == '35') {
      // 气费账单
      // intoCGPage(CGRouteSetting.home_query_gas_order, arguments: {'queryType': 0});
    } else if (url == '36') {
      // 自助抄表
      // intoCGPage(CGRouteSetting.home_query_gas_order, arguments: {'queryType': 2});
    } else if (url == '37') {
      // 供暖缴费
      // intoCGPage(CGRouteSetting.heat_home_page);
    } else if (url == '38') {
      // 账单代扣
      // intoCGPage(CGRouteSetting.home_query_gas_order, arguments: {'queryType': 1});
    } else if (url == '39') {
      // 话费充值
      // intoCGPage(CGRouteSetting.home_recharge_phone);
    }
  }
}

//跳转到中燃页面
void intoCGPage(String pageName, {arguments}) async {
  /*await gasLoginCheck(SpUtil.getString('usr_phone_num'), SpUtil.getInt('time_stamp'),
      SpUtil.getString('sign')).then((value) {
        if (!value) {
          Get.toNamed(RouteConfig.mallLogin);
          return;
        }
      });
  if (pageName == CGRouteSetting.home_recharge_phone) {
    Get.toNamed(CGRouteSetting.home_recharge_phone,
        arguments: {
          'title': '手机充值',
          'url': CGCommonMacro.CGHSHPhoneRecharge +
              '&openId=' +
              (UserInfoManager.instance.id ?? '')
        });
  } else {
    Get.toNamed(pageName, arguments: arguments);
  }*/
}

// 缓存图片
Widget cacheImage({
  String imageUrl,
  BoxFit fit,
  double width,
  double height,
  bool crop = false,
}) {
  if (imageUrl == null) {
    imageUrl = '';
  }
  return CachedNetworkImage(
    width: width,
    height: height,
    fit: fit,
    imageUrl: imageUrl,
    placeholder: (context, url) => SizedBox(),
    errorWidget: (context, url, error) => SizedBox(),
  );
}

/// 十六进制颜色，
Color hexToColor(String hex, {double opacity = 1}) {
  assert(RegExp(r'^#([0-9a-fA-F]{6})|([0-9a-fA-F]{8})$').hasMatch(hex),
      'hex color must be #rrggbb or #rrggbbaa');

  return Color(
    int.parse(hex.substring(1), radix: 16) +
        (hex.length == 7 ? 0xff000000 : 0x00000000),
  ).withOpacity(opacity);
}

void getAndGoThirdShop(int shopId) {
  var params = {
    "data_sign": 0,
    "channel_num_id": 99,
    "use_platform": 2,
    "access_token": SpUtil.getString("token"),
    "ec_shop_num_id": shopId.toString(),
  };
  SpUtil.putInt('thirdStoreShopNum', shopId);
  print(">>>>>!!!!!>$params");
  Api.getShopInfo(params).listen((event) {
    if (event != null && event['code'] == 0) {
      // toast("2222");

      if (event['ec_shop_infos'].length > 0) {
        SpUtil.remove(Config.GET_SHOP_INFO);
        var shoplistes = event['ec_shop_infos'];
        SpUtil.putObject(Config.GET_SHOP_INFO, {
          'shop_name': shoplistes[0]['ec_shop_name'],
          'shop_id': shoplistes[0]['ec_shop_num_id'],
          'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
          'is_get_home': shoplistes[0]['is_get_home'],
          'is_express': shoplistes[0]['is_express'],
          'service_telphone': shoplistes[0]['service_telphone'],
          'is_pick_up': shoplistes[0]['is_pick_up'],
          'adr': shoplistes[0]['adr'],
          'telphone': shoplistes[0]['telphone'],
          'pickAdrId': shoplistes[0]['sub_unit_num_id'],
          'offShopName': shoplistes[0]['sub_unit_name'],
          'offShopadr': shoplistes[0]['sub_unit_adr'],
          'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
          'isSupporySacn': true,
          'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
          'is_express_shops':
              shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
          'prv_num_id': shoplistes[0]['prv_num_id'],
          'prv_name': shoplistes[0]['prv_name'],
          'city_num_id': shoplistes[0]['city_num_id'],
          'city_name': shoplistes[0]['city_name'],
          'city_area_num_id': shoplistes[0]['city_area_num_id'],
          'city_area_name': shoplistes[0]['city_area_name'],
          'ec_shop_logo': shoplistes[0]['ec_shop_logo']
        });
        SpUtil.putInt(Config.IS_CHANGE_SHOP,
            SpUtil.getInt('storeShopNum') == shopId ? 0 : 1);
        // toast("1111");
        Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
      }
    } else {
      toast(event['massage']);
    }
  });
}
